package cn.bdqn.web.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



import cn.bdqn.entity.AppCategory;
import cn.bdqn.entity.AppInfo;
import cn.bdqn.entity.AppVersion;
import cn.bdqn.entity.DataDictionary;
import cn.bdqn.service.AppCategoryService;
import cn.bdqn.service.AppInfoService;
import cn.bdqn.service.AppVersionService;
import cn.bdqn.service.DictionaryService;
import cn.bdqn.utils.PageBean;


@Controller
@RequestMapping("/devApp")
public class DevAppController {
	
	
	//字典表的service层
	@Autowired
	private DictionaryService dictionaryService;
	
	//分类表的service层
	@Autowired
	private AppCategoryService appCategoryService;
	
	//app信息的service
	@Autowired
	private AppInfoService appInfoService;
	
	//app版本信息的service
	@Autowired
	private AppVersionService appVersionService;
	
	@RequestMapping("/disMain")
	public String disMain() throws Exception{
		
		return "dev/main";
	}
	
	
	//显示app信息页面
	@RequestMapping("/appInfoList")
	public String appInfoList(Model model,
							  @RequestParam(value="softwareName",required=false)String checkSoftwareName,
							  @RequestParam(value="status",required=false)String checkStatus,
							  @RequestParam(value="flatform",required=false)String checkFlatform,
							  @RequestParam(value="level1",required=false)String checkLevel1,
							  @RequestParam(value="level2",required=false)String checkLevel2,
							  @RequestParam(value="level3",required=false)String checkLevel3,
							  @RequestParam(value="currentPage",required=false)String currentPage,
							  @RequestParam(value="pageSize",required=false)String pageSize)
									  throws Exception{
		//1.app状态
		List<DataDictionary> statusList = dictionaryService.findAllStatus("APP_STATUS");
		//1.放到model中
		model.addAttribute("statusList", statusList);
		//2.所属平台
		List<DataDictionary> flatformList = dictionaryService.findAllStatus("APP_FLATFORM");
		//2.放到model中
		model.addAttribute("flatformList", flatformList);
		//3.查询1级分类
		List<AppCategory> level1List = appCategoryService.findAllLevelOne();
		//3.放到model中
		model.addAttribute("level1List", level1List);
		//4.查询所有app的信息
		//4.1封装查询数据
		Map<String,Object> checkMap = new HashMap<>();
		checkMap.put("softwareName", checkSoftwareName);
		checkMap.put("status", checkStatus);
		checkMap.put("flatform", checkFlatform);
		checkMap.put("level1", checkLevel1);
		checkMap.put("level2", checkLevel2);
		checkMap.put("level3", checkLevel3);
		checkMap.put("currentPage", currentPage);
		checkMap.put("pageSize", pageSize);
		PageBean<AppInfo> pageBean = appInfoService.findAll(checkMap);
		//4.放到model中
		model.addAttribute("pageBean", pageBean);
		//5.为了数据回显,讲map放到model中
		model.addAttribute("checkMap", checkMap);
		//6.为了二级和三级回显 将二级三级从新查询出来
		List<AppCategory> level2List = findLevelNoJson(checkLevel1);
		List<AppCategory> level3List = findLevelNoJson(checkLevel2);
		//6.放入model中
		model.addAttribute("level2List", level2List);
		model.addAttribute("level3List", level3List);
		return "dev/appInfoList";
	}
	
//	三级联动
	@RequestMapping("/findLevel")
	public @ResponseBody List<AppCategory> findLevel(@RequestBody Map<String,String> map) throws Exception{
		//获得查询的条件
		String parentId = map.get("parentId");
//		调用方法查询
		List<AppCategory> levelList = appCategoryService.findAllLevelByParentId(parentId);
		
		return levelList;
	}
	public List<AppCategory> findLevelNoJson(String parentId) throws Exception{
//		调用方法查询
		List<AppCategory> levelList = appCategoryService.findAllLevelByParentId(parentId);
		return levelList;
	}
	//跳转到添加页面
	@RequestMapping("/disAppInfoAdd")
	public String disAppInfoAdd(Model model) throws Exception{
		//1.所属平台
		List<DataDictionary> flatformList = dictionaryService.findAllStatus("APP_FLATFORM");
		//1.放到model中
		model.addAttribute("flatformList", flatformList);
		
		//2.查询1级分类
		List<AppCategory> level1List = appCategoryService.findAllLevelOne();
		//2.放到model中
		model.addAttribute("level1List", level1List);
		
		return "dev/appInfoAdd";
	}
	
	//异步校验apkname是否唯一
	@RequestMapping("/checkApkName")
	public @ResponseBody Map<String,String> checkApkName(@RequestBody Map<String,String> map) throws Exception{
		//接收传过来的apkname
		String apkname = map.get("apkname");
		//根据apkname查询是否唯一
		int count = appInfoService.findAppInfoByApkname(apkname);
		Map<String,String> returnMap = new HashMap<>();
		if(count == 0){
			//可以使用
			returnMap.put("apkInfo", "0");
		}else{
			//已经存在
			returnMap.put("apkInfo", "1");
		}
		return returnMap;
	}
	
	
	
	//添加功能
	@RequestMapping("/appInfoAdd")
	public String appInfoAdd(AppInfo appInfo,MultipartFile picFile,Model model,HttpSession session) throws Exception{
//		if(picFile.getSize() > 0 && picFile.getSize() < (50 * 1024))
		if(picFile.getSize()>0){
			//获得图片原名字,获得后缀,判断是否符合要求
			String oldName = picFile.getOriginalFilename();
			String typeName = oldName.substring(oldName.lastIndexOf(".")).toLowerCase();
			//要求图片的格式必须是  .jpg/.png/.jpeg
			if(!(".jpg".equals(typeName) || ".png".equals(typeName)  || ".jpeg".equals(typeName))){
				//图片的格式错误,给予提示
				model.addAttribute("picInfo", "图片格式不正确.....");
				return "forward:/devApp/disAppInfoAdd";
			}
//			给图片创建新名字
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String prefixName = sdf.format(new Date());
			String suffixName = UUID.randomUUID().toString();
			//新名字
			String newName = prefixName + suffixName + typeName;
			//
			//保存图片......
			picFile.transferTo(new File("D:\\Demopic\\"+newName));
			//讲图片信息保存到appInfo对象中
			appInfo.setLogopicpath("http://localhost:8080/Demopic/"+newName);//项目路径
			appInfo.setLogolocpath("D:\\Demopic\\"+newName);
		}
		
//		DevUser devUser = (DevUser) session.getAttribute("devUser");
		
		appInfo.setDevid(1L);
		appInfo.setCreatedby(1L);
		
		Integer count = appInfoService.save(appInfo);
		if(count > 0){
			return "redirect:/devApp/appInfoList";
		}else{
			model.addAttribute("saveInfo", "系统正在更新.....");
			return "forward:/devApp/disAppInfoAdd";
		}
	}
	
	
	
	//跳转到修改页面
	@RequestMapping("/disAppInfoUpdate/{id}")
	public String disAppInfoUpdate(@PathVariable("id")Integer id,Model model) throws Exception{
		//需要数据回显
		//1.通过id查询app的基础信息
		AppInfo appInfo = appInfoService.findAppInfoById(id);
		//1.放到model中
		model.addAttribute("appInfo", appInfo);
		//2.所属平台
		List<DataDictionary> flatformList = dictionaryService.findAllStatus("APP_FLATFORM");
		//2.放到model中
		model.addAttribute("flatformList", flatformList);
		//3.查询1级分类
		List<AppCategory> level1List = appCategoryService.findAllLevelOne();
		//3.放到model中
		model.addAttribute("level1List", level1List);
		//4.为了二级和三级回显 将二级三级从新查询出来
		List<AppCategory> level2List = findLevelNoJson(appInfo.getCategorylevel1()+"");
		List<AppCategory> level3List = findLevelNoJson(appInfo.getCategorylevel2()+"");
		//4.放入model中
		model.addAttribute("level2List", level2List);
		model.addAttribute("level3List", level3List);
		return "dev/appInfoUpdate";
	}
	
	
	
	//修改APP基础信息
	@RequestMapping("/appInfoUpdate")
	public String appInfoUpdate(AppInfo appInfo,MultipartFile picFile,Model model,HttpSession session) throws Exception{
		//修改app	
		//修改文件了
//		if(picFile.getSize() > 0 && picFile.getSize() < (50 * 1024))
		if(picFile.getSize() > 0){
			//获得元名字
			String oldName = picFile.getOriginalFilename();
			String typeName = oldName.substring(oldName.lastIndexOf(".")).toLowerCase();
			//要求图片的格式必须是  .jpg/.png/.jpeg
			if(!(".jpg".equals(typeName) || ".png".equals(typeName)  || ".jpeg".equals(typeName))){
				//图片的格式错误,给予提示
				model.addAttribute("picInfo", "图片格式不正确.....");
				return "forward:/devApp/disAppInfoAdd";
			}
			//获得图片在服务器中的名字
			String serverPicName = appInfoService.findAppInfoPicpathById(appInfo.getId());
			
			String newName = serverPicName.substring(serverPicName.lastIndexOf("/") + 1, serverPicName.lastIndexOf(".")) + typeName;
			
			File file = new File("E:\\ssmPic\\"+newName);
			//文件转移
			picFile.transferTo(file);
			
			appInfo.setLogopicpath("http://localhost:8080/pic/" + newName);
			appInfo.setLogolocpath("E:\\ssmPic\\" + newName);
		}
		/*DevUser devUser = (DevUser) session.getAttribute("devUser");*/
		
		appInfo.setModifyby(1L);
		
		Integer count = appInfoService.update(appInfo);
		if(count > 0){
			return "redirect:/devApp/appInfoList";
		}else{
			model.addAttribute("saveInfo", "系统正在更新.....");
			return "forward:/devApp/disAppInfoUpdate";
		}
	}
	
	
	
  @RequestMapping("/download")    
    public ResponseEntity<byte[]> download() throws Exception {    
        String path="E:\\ssmPic\\20170627085912df45dbb8-96ab-4d3f-8371-d6cd47e2513f.jpg";  
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String("20170627085912df45dbb8-96ab-4d3f-8371-d6cd47e2513f.jpg");//为了解决中文名称乱码问题  
        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }  
	
	
	
	
	//跳转新增App版本页面
    @RequestMapping("/disAppInfoAddVersion/{id}")
    public String disAppInfoAddVersion(@PathVariable("id")Integer id,Model model) throws Exception{
    	//1.通过app的id查询对应的版本信息
    	List<AppVersion> appVersionList = appVersionService.findAllVersionByAppInfoId(id);
    	//1.放到Model中
    	model.addAttribute("appVersionList", appVersionList);
    	
    	
    	//2.id放到model中
    	model.addAttribute("appId",id);
    	
    	
    	return "dev/appInfoAddVersion";
    }
	
	
	
	
	
	//新增app版本信息
    @RequestMapping("/appInfoAddVersion")
    public String appInfoAddVersion(AppVersion appVersion,MultipartFile apkFile,Model model) throws Exception{
    	if(apkFile.getSize() > 0){
			//获得元名字
			String oldName = apkFile.getOriginalFilename();
			String typeName = oldName.substring(oldName.lastIndexOf(".")).toLowerCase();
			//要求图片的格式必须是  .jpg/.png/.jpeg
			if(!(".apk".equals(typeName))){
				//图片的格式错误,给予提示
				model.addAttribute("apkInfo", "文件格式不正确.....");
				return "forward:/devApp/disAppInfoAddVersion/"+appVersion.getAppid();
			}
			//获得当前app信息的apkName+app的版本号 + .apk
			String apkName = appInfoService.findAPKNameById(appVersion.getAppid());
			String versionName = appVersion.getVersionno();
			String newName = apkName + "-" + versionName + typeName;
			
			File file = new File("D:\\Demopic\\"+newName);
			//文件转移
			apkFile.transferTo(file);
			appVersion.setDownloadlink("http://localhost:8080/Demopic/" + newName);
			appVersion.setApklocpath("D:\\Demopic\\"+newName);
		}
    	
    	appVersion.setCreatedby(1L);
    	
		Integer count = appVersionService.save(appVersion);
		if(count > 0){
			return "redirect:/devApp/appInfoList";
		}else{
			model.addAttribute("saveInfo", "系统正在更新.....");
			return "forward:/devApp/disAppInfoAddVersion/"+appVersion.getAppid();
		}
    	
    }
    
    //ajax检查是否有版本信息
    @RequestMapping("/checkVersion")
    @ResponseBody
    public String checkVersion(Integer appid) throws Exception
    {
    	List<AppVersion> appVersionList = appVersionService.findAllVersionByAppInfoId(appid);
    	if (appVersionList.size()==0) {
  			return "false";
		}else {
			return "true";
		}
    }
    
    //跳转修改APP版本信息！
  @RequestMapping("/disAppInfoUpdateVersion/{id}")
  public String appInfoUpdateVersion(@PathVariable("id") Integer id,Model model) throws Exception
  {
	  	List<AppVersion> appVersionList = appVersionService.findAllVersionByAppInfoId(id);
  		//1.放到Model中
  		model.addAttribute("appVersionList", appVersionList);
  		AppVersion appVersion=appVersionService.findVersionByAppInfoId(id);
  		model.addAttribute("appVersions", appVersion);
  		return "dev/appInfoUpdateVersion";
  }
  //修改App版本信息
  @RequestMapping("/appInfoUpdateVersion")
  public String appInfoUpdateVersion(AppVersion appVersion,MultipartFile apkFile,Model model) throws Exception
  {
	  if(apkFile.getSize() > 0){
			//获得元名字
			String oldName = apkFile.getOriginalFilename();
			String typeName = oldName.substring(oldName.lastIndexOf(".")).toLowerCase();
			//要求图片的格式必须是  .jpg/.png/.jpeg
			if(!(".apk".equals(typeName))){
				//图片的格式错误,给予提示
				model.addAttribute("apkInfo", "文件格式不正确.....");
				return "forward://disAppInfoUpdateVersion/"+appVersion.getAppid();
			}
			//获得当前app信息的apkName+app的版本号 + .apk
			String apkName = appInfoService.findAPKNameById(appVersion.getAppid());
			String versionName = appVersion.getVersionno();
			String newName = apkName + "-" + versionName + typeName;
			
			File file = new File("D:\\Demopic\\"+newName);
			//文件转移
			apkFile.transferTo(file);
			appVersion.setModifyby(1L);
			appVersion.setApkfilename(newName);
			appVersion.setDownloadlink("http://localhost:8080/Demopic/" + newName);
			appVersion.setApklocpath("D:\\Demopic\\"+newName);
		}
	  int count=appVersionService.updateAppVersion(appVersion);
		  if (count>0) {
			return "redirect://appInfoList";
		}else
		{
			model.addAttribute("saveInfo", "系统正在更新，修改失败！");
			return "forward://disAppInfoUpdateVersion/"+appVersion.getAppid();
		}
  }
	
  //查看所有app信息
  @RequestMapping("/disShowAppInfo/{id}")
  public String disShowAppInfo(@PathVariable("id") Integer id,Model model) throws Exception
  {
	 AppInfo appInfo=appInfoService.findAppInfoById(id);
	  model.addAttribute("appInfo", appInfo);
	  List<AppVersion> appVersionList = appVersionService.findAllVersionByAppInfoId(id);
		//1.放到Model中
	model.addAttribute("appVersionList", appVersionList);
	  return "dev/showAppInfo";
  }
  //根据id删除APP信息
  @RequestMapping("/delAppInfo/{appid}")
  public String delAppInfo(@PathVariable("appid")Integer appid,Model model) throws Exception
  {
	  int i=appVersionService.delAppVersionInfo(appid);
	  if (i>0) {
		int c=appInfoService.delAppInfo(appid);
		if (c>0) {
			model.addAttribute("delInfo", "删除成功");
		}else {
			model.addAttribute("delInfo", "系统正在更新，请联系管理员...");
		}
	  }else
	  {
		 model.addAttribute("delInfo", "系统正在更新，请联系管理员...");
	  }
	  return "forward://appInfoList";
  }

  
//上架修改
	@RequestMapping("/appStatusNameUpdateUp")
	public @ResponseBody Map<String, Long> appStatusNameUpdateUp(@RequestBody Map<String, Long> map)
	throws Exception
	{
         long id=map.get("id");
         long count= appInfoService.updateAppStatusName(id);
          Map<String, Long> returnMap = new HashMap<>();
		if (count!=0) {
			//修改成功
			returnMap.put("status", 0L);
		}else{
			//修改失败
			returnMap.put("status", 1L);
		}
		
		
		
		
		return returnMap;
				
	}
	
	//下架修改
		@RequestMapping("/appStatusNameUpdateDown")
		public @ResponseBody Map<String, Long> appStatusNameUpdateDown(@RequestBody Map<String, Long> map) throws Exception{
	         long id=map.get("id");
	         long count= appInfoService.updateAppStatusNameDown(id);
	          Map<String, Long> returnMap = new HashMap<>();
			if (count!=0) {
				//修改成功
				returnMap.put("status", 0L);
			}else{
				//修改失败
				returnMap.put("status", 1L);
			}
			
			
			
			
			return returnMap;
					
		}

	
}
